package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.dto.RoleDTO;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TimeUtil;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.system.constants.DyRoleKeyConstants;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.bo.DyAnchorBo;
import com.ruoyi.system.domain.bo.DyAnchorPhotoBo;
import com.ruoyi.system.domain.bo.DyAnchorRelEditBo;
import com.ruoyi.system.domain.bo.DyCustomerSumBo;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IDyAnchorPhotoService;
import com.ruoyi.system.service.IDyAnchorService;
import com.ruoyi.system.service.IDyCommonService;
import com.ruoyi.system.service.ISysOssService;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 主播Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-20
 */
@RequiredArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class DyAnchorPhotoServiceImpl implements IDyAnchorPhotoService {

    private final DyAnchorPhotoMapper dyAnchorPhotoMapper;

    private final DyAnchorPhotoDetailMapper dyAnchorPhotoDetailMapper;

    private final DyAnchorMapper dyAnchorMapper;

    private final DyClientAnchorMapper dyClientAnchorMapper;

    @Resource
    private IDyCommonService iDyCommonService;

    @Override
    public TableDataInfo<DyAnchorPhoto> queryPageList(DyAnchorPhotoBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null){
            throw new ServiceException("用户未登录");
        }

        RoleDTO roleDTO = iDyCommonService.getFirstRole(loginUser.getRoles());
        if (ObjectUtil.isEmpty(roleDTO)){
            throw new ServiceException("无数据查看权限");
        }

        Page<DyAnchorPhoto> dyAnchorPhotoPage = dyAnchorPhotoMapper
                .selectPage(pageQuery.build(), new QueryWrapper<DyAnchorPhoto>().lambda()
                        .eq(bo.getAnchorId() != null, DyAnchorPhoto::getAnchorId, bo.getAnchorId())
                        .orderByDesc(BaseEntity::getCreateTime));

        return TableDataInfo.build(dyAnchorPhotoPage);
    }


    @Override
    public Boolean insertByBo(DyAnchorPhotoBo bo) {

        DyAnchorPhoto add = BeanUtil.toBean(bo, DyAnchorPhoto.class);

        DyAnchor anchor = dyAnchorMapper.selectById(bo.getAnchorId());
        add.setAnchorName(anchor.getName());
        add.setPhotoNum(bo.getDetails().size());

        boolean b = dyAnchorPhotoMapper.insert(add) > 0;
        if (!b){
            throw new ServiceException("保存主播照片失败！");
        }

        for (DyAnchorPhotoDetail detail : bo.getDetails()) {

            if (StrUtil.isEmpty(detail.getPhotoUrl())){
                throw new ServiceException("照片url为空！");
            }

            detail.setAnchorId(add.getAnchorId());
            detail.setAnchorPhotoId(add.getId());
        }

        dyAnchorPhotoDetailMapper.insertBatch(bo.getDetails());

        //更新时间
        List<DyClientAnchor> anchors = dyClientAnchorMapper.selectList(new QueryWrapper<DyClientAnchor>().lambda().eq(DyClientAnchor::getAnchorId, add.getAnchorId()));
        if (CollUtil.isNotEmpty(anchors)){
            for (DyClientAnchor clientAnchor : anchors) {
                clientAnchor.setNewestTime(bo.getNewestTime());
                dyClientAnchorMapper.updateById(clientAnchor);
            }
        }

        return b;
    }

    @Override
    public Boolean updateByBo(DyAnchorPhotoBo bo) {

        DyAnchorPhoto update = BeanUtil.toBean(bo, DyAnchorPhoto.class);

        DyAnchorPhoto photo = dyAnchorPhotoMapper.selectById(update.getId());
        if (photo == null){
            throw new ServiceException("主播照片数据已被删除！");
        }

        DyAnchor anchor = dyAnchorMapper.selectById(bo.getAnchorId());
        update.setAnchorName(anchor.getName());
        update.setPhotoNum(bo.getDetails().size());

        boolean b = dyAnchorPhotoMapper.updateById(update) > 0;
        if (!b){
            throw new ServiceException("主播照片更新失败！");
        }

        dyAnchorPhotoDetailMapper.delete(new QueryWrapper<DyAnchorPhotoDetail>().lambda().eq(DyAnchorPhotoDetail::getAnchorPhotoId, photo.getId()));

        for (DyAnchorPhotoDetail detail : bo.getDetails()) {

            if (StrUtil.isEmpty(detail.getPhotoUrl())){
                throw new ServiceException("照片url为空！");
            }

            detail.setAnchorId(update.getAnchorId());
            detail.setAnchorPhotoId(update.getId());
        }

        dyAnchorPhotoDetailMapper.insertBatch(bo.getDetails());

        return b;
    }

    @Override
    public DyAnchorPhotoBo getAnchorPhotoById(DyAnchorPhotoBo bo) {

        if (bo.getId() == null){
            throw new ServiceException("查询的用户数据不存在！");
        }

        DyAnchorPhoto photo = dyAnchorPhotoMapper.selectById(bo.getId());

        DyAnchorPhotoBo photoBo = BeanUtil.toBean(photo, DyAnchorPhotoBo.class);

        List<DyAnchorPhotoDetail> details = dyAnchorPhotoDetailMapper.selectList(new QueryWrapper<DyAnchorPhotoDetail>().lambda().eq(DyAnchorPhotoDetail::getAnchorPhotoId, photo.getId()).orderByDesc(BaseEntity::getCreateTime));
        photoBo.setDetails(details);

        return photoBo;
    }

    @Override
    public int delAnchorPhoto(DyAnchorPhotoBo bo) {

        if (bo.getId() == null){
            throw new ServiceException("删除的用户数据不存在！");
        }

        int i = dyAnchorPhotoMapper.deleteById(bo.getId());

        dyAnchorPhotoDetailMapper.delete(new QueryWrapper<DyAnchorPhotoDetail>().lambda().eq(DyAnchorPhotoDetail::getAnchorPhotoId, bo.getId()));

        return i;
    }

    @Override
    public DyAnchorPhoto getNewestAnchorPhoto(Long anchorId) {
        return dyAnchorPhotoMapper.selectOne(new LambdaQueryWrapper<DyAnchorPhoto>().eq(DyAnchorPhoto::getAnchorId, anchorId).orderByDesc(DyAnchorPhoto::getNewestTime).last(" limit 1"));
    }

}
